package com.speedy.course.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.sqlite.db.SupportSQLiteDatabase
import com.speedy.course.CourseApplication
import com.speedy.course.constant.WeekDay
import com.speedy.course.constant.WeekType
import com.speedy.course.db.converter.RoomConverter
import com.speedy.course.db.dao.LessonDao
import com.speedy.course.db.dao.TaskDao
import com.speedy.course.db.entity.Lesson
import com.speedy.course.db.entity.Task
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Database(entities = [Lesson::class, Task::class], version = AppDatabase.DB_VERSION, exportSchema = false)
@TypeConverters(RoomConverter::class)
abstract class AppDatabase : RoomDatabase() {

    abstract fun getLessonDao():LessonDao
    abstract fun getTaskDao(): TaskDao


    companion object{

        private const val DB_NAME = "smart-course.db"

        const val DB_VERSION = 1

        @Volatile
        private var instance: AppDatabase? = null


        fun getInstance(): AppDatabase {
            return instance ?: synchronized(this) {
                instance ?: buildDatabase(CourseApplication.get()).also { instance = it }
            }
        }

        private fun buildDatabase(context: Context): AppDatabase {
            return Room.databaseBuilder(context,AppDatabase::class.java,DB_NAME)
                .fallbackToDestructiveMigration()
                .setJournalMode(JournalMode.WRITE_AHEAD_LOGGING)
                .addCallback(object :Callback(){
                    override fun onCreate(db: SupportSQLiteDatabase) {
                        super.onCreate(db)
                        getInstance().initDatabase()
                    }
                })
                .build()
        }



    }

    private fun initDatabase() {
        CoroutineScope(Dispatchers.IO).launch {
            var lessonDao = getLessonDao()
            lessonDao.insert(Lesson(WeekDay.MONDAY,8,0))
            lessonDao.insert(Lesson(WeekDay.MONDAY,9,0))
            lessonDao.insert(Lesson(WeekDay.MONDAY,10,0))
            lessonDao.insert(Lesson(WeekDay.MONDAY,11,0))
            lessonDao.insert(Lesson(WeekDay.MONDAY,12,0))
            lessonDao.insert(Lesson(WeekDay.MONDAY,14,0))
            lessonDao.insert(Lesson(WeekDay.MONDAY,15,0))
            lessonDao.insert(Lesson(WeekDay.MONDAY,16,0))
        }
    }

}